import React, { useState } from 'react';
import { SettingOutlined, ProductOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from "react-router-dom";
import { Menu } from 'antd';
import type { MenuProps } from 'antd';



const items: MenuProps['items'] = [
  {
    key: "/setting",
    icon: <SettingOutlined />,
    children: [
      { key: "/account", icon: null, label: "账号管理" },
      { key: "/user", icon: null, label: "用户管理" }],
    label: "设置"
  },
  {
    key: "/operations",
    icon: <ProductOutlined />,
    children: [
      { key: "/information", icon: null, label: "资讯管理" },
      { key: "/resource", icon: null, label: "资源管理" },
      { key: "/banner", icon: null, label: "Banner配置" },
      { key: "/classification", icon: null, label: "分类管理" },
    ],
    label: "运营配置"
  }
];

interface LevelKeysProps {
  key?: string;
  children?: LevelKeysProps[];
}
const getLevelKeys = (items1: LevelKeysProps[]) => {
  const key: Record<string, number> = {};
  const func = (items2: LevelKeysProps[], level = 1) => {
    items2.forEach((item) => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        return func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};

const levelKeys = getLevelKeys(items as LevelKeysProps[]);

const MenuComponent: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [stateOpenKeys, setStateOpenKeys] = useState<string[]>([]);
  const onOpenChange: MenuProps['onOpenChange'] = (openKeys) => {
    const currentOpenKey = openKeys.find((key) => stateOpenKeys.indexOf(key) === -1);
    if (currentOpenKey !== undefined) {
      const repeatIndex = openKeys
        .filter((key) => key !== currentOpenKey)
        .findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);
      setStateOpenKeys(
        openKeys
          .filter((_, index) => index !== repeatIndex)
          .filter((key) => levelKeys[key] <= levelKeys[currentOpenKey]),
      );
    } else {
      setStateOpenKeys(openKeys);
    }
  };
  // 点击跳转
  const onClick: MenuProps['onClick'] = (e) => {
    navigate(e.key)
  };

  return (
    <Menu
      onClick={onClick}
      defaultSelectedKeys={[location.pathname]}
      openKeys={stateOpenKeys}
      onOpenChange={onOpenChange}
      mode="inline"
      theme="dark"
      items={items}
    />
  );
};

export default MenuComponent;